package cn.jee.controller;

import cn.jee.entity.Product;
import cn.jee.entity.User;
import cn.jee.repository.ProductRepository;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Controller
public class ProductController {

  @Autowired
  private ProductRepository productRepository;

  //得到所有商品
//  @GetMapping("/products")
//  public String getAllProducts(Model model) {
//    List<Product> products = productRepository.findAll();
//    model.addAttribute("products", products);
//    return "product_list";
//  }
  @GetMapping("/products")
  public String getAllProducts(@RequestParam("username") String username,
                               HttpSession session,
                               Model model) {
    User user = (User) session.getAttribute("user");
    model.addAttribute("user", user); // 确保user在model中

    List<Product> products = productRepository.findAll();
    model.addAttribute("products", products);
    return "product_list";
  }
  //显示输入页面
  @GetMapping("/products/new")
  public String showCreateForm(@RequestParam("username") String username,
                              HttpSession session,
                              Model model) {
    User user = (User) session.getAttribute("user");
    model.addAttribute("user", user);
    model.addAttribute("product", new Product());
    return "product_form";
  }


  //校验与保存
  // 文件名：ProductController.java（继续添加）
//  @PostMapping("/products")
//  public String createProduct(@Valid @ModelAttribute Product product,
//                              BindingResult result) {
//    if (result.hasErrors()) {
//      return "product_form";
//    }
//    productRepository.save(product);
//    return "redirect:/products";
//  }
  @PostMapping("/products")
  public String createProduct(@Valid @ModelAttribute Product product,
                              BindingResult result,
                              Model model,
                              HttpSession session) {
    if (result.hasErrors()) {
      User user = (User) session.getAttribute("user");
      model.addAttribute("user", user);
      model.addAttribute("product", product);
      return "product_form";
    }
    productRepository.save(product);
    User user = (User) session.getAttribute("user");
    return "redirect:/products?username=" + user.getUsername();
  }

}
